package com.cjp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjp.pojo.Result;
import com.cjp.pojo.User;
import com.cjp.service.IUserService;
import com.cjp.utils.JwtUtil;
import com.cjp.utils.Md5Util;
import com.cjp.utils.ThreadLocalUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
@Validated
public class UserController {

    private final IUserService userService;

    private final RedisTemplate redisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        // 根据 username 获取 User
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .eq(username != null, User::getUsername, username);
        User user = userService.getOne(queryWrapper);

        if(user == null) {
            // 注册该用户
            userService.register(username, password);
        }
        else {
            return Result.error("用户已存在，注册失败！");
        }
        return Result.success();
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<User>()
                .eq(username != null, User::getUsername, username);
        User user = userService.getOne(queryWrapper);

        String token = null;
        if(user == null) {
            return Result.success("账号不存在！");
        }
        else{
            if(Md5Util.getMD5String(password).equals(user.getPassword())) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", user.getId());
                map.put("username", user.getUsername());

                token = JwtUtil.genToken(map);
                // 将 token 保存到 Redis
                redisTemplate.opsForValue().set("token", token, 12, TimeUnit.HOURS);
            }
            else{
                return Result.success("密码错误！");
            }
        }
        return Result.success(token);
    }

    @GetMapping("/userInfo")
    public Result<User> getUserInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        User user = userService.getById(Long.valueOf(String.valueOf(map.get("id"))));
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@URL String avatarUrl) {
        Map<String,Object> claims = ThreadLocalUtil.get();
        Long id = Long.valueOf(claims.get("id").toString());
        User user = User.builder()
                .id(id)
                .userPic(avatarUrl)
                .updateTime(LocalDateTime.now())
                .build();
        userService.updateById(user);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> map) {
        String old_pwd = map.get("old_pwd");
        String new_pwd = map.get("new_pwd");
        String re_pwd = map.get("re_pwd");
        if(old_pwd == null || new_pwd == null || re_pwd == null) {
            return Result.error("缺少必要参数！");
        }

        Map<String, Object> claims = ThreadLocalUtil.get();
        User user = userService.getById(Long.valueOf(claims.get("id").toString()));

        if(!user.getPassword().equals(Md5Util.getMD5String(old_pwd))) {
            return Result.error("原密码错误！");
        }

        if(!new_pwd.equals(re_pwd)) {
            return Result.error("两个密码不一致！");
        }

        user.setPassword(Md5Util.getMD5String(new_pwd));
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);

        redisTemplate.opsForValue().getOperations().delete("token");

        return Result.success();
    }
}
